
#include <wordexp.h>
#include "expandPath.h"
#include "fileExists.h"
#include <vector>
#include <string>



//std::string recursiveExpantion( char const * path );

std::vector<std::string> expandPath( char const * PathToBeMatched, bool doRecursive, char const * sub );


std::vector<std::string> expandPath( std::string PathToBeMatched, bool doRecursive, std::string subMatch ) {

  if ( doRecursive )
    PathToBeMatched.append("/*");
  char const *__PathToBeMatched = PathToBeMatched.c_str();
  wordexp_t p;
  char **w;
  unsigned int i;
  std::vector<std::string> result;

  wordexp(__PathToBeMatched, &p, WRDE_SHOWERR);
  w = p.we_wordv;


  for (i=0; i<p.we_wordc; i++) {
    if ( fileExists(w[i]) == true) {

      std::vector<std::string> temp;
      if ( doRecursive ) {
        temp = expandPath( w[i], true, subMatch.c_str() );
      }

      std::string res = w[i];
      if ( subMatch.size()==0 || res.find( subMatch )!=std::string::npos )
        result.push_back(w[i]);
  
      if (temp.size()>0)
        for (size_t j=0; j< temp.size(); j++) {
          if ( subMatch.size()==0 || temp[j].find(subMatch)!=std::string::npos )
            result.push_back(temp[j]);
          }
    }
  }
  wordfree(&p);

  return result;
}

std::vector<std::string> expandPath( char const * PathToBeMatched, bool doRecursive, char const * sub ) {

  std::string newName = PathToBeMatched;
  std::string nesSub = sub;
  return expandPath( newName, doRecursive, sub );
}
//std::vector<std::string> recursiveExpantion( char const * path )  {

  

//}
